﻿
/*
 * 类    名：CreateTxSQL
 * 
 * 功能描述：实体转化SQL工厂
 * 
 * 创 建 者：CHZ
 * 
 * 创建日期：2012.8.12
 * 
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;


namespace PUBCOM
{
    public class CreateTxSQL
    {
        
        #region 检测

        /// <summary>
        /// 单表多条件查询
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="fileds"></param>
        /// <returns></returns>
        public static SQLObject IC_Exists_SQL(object obj, Dictionary<string, object> fileds)
        {
            StringBuilder sql = new StringBuilder();
            List<SqlParameter> Parms = new List<SqlParameter>();
            string _ParmaryKey = GetParmary(obj);
            foreach (string key in fileds.Keys)
            {
                sql.Append(key + "=@" + key + " and ");
                Parms.Add(new SqlParameter(key, fileds[key]));
            }
            return new SQLObject(string.Format("select count({0}) from {1} where {2}", _ParmaryKey, GetObjectBinderTableName(obj.GetType()), _ParmaryKey + sql.ToString().Trim().Trim("and".ToCharArray())), Parms.ToArray());
        }

        /// <summary>
        /// 多表多条件联合查询
        /// </summary>
        /// <param name="lambda"></param>
        /// <param name="parms"></param>
        /// <returns></returns>
        public static string IC_Existes_SQL(LambdaExpression lambda)
        {
            string where = ExpressionProvider.ToSql(lambda.Body);
            return string.Format("select count(1) from {0} {1}", GetTables(lambda.Parameters), (!string.IsNullOrEmpty(where) ? " where " + where : ""));
        }

        /// <summary>
        ///  返回最大值
        /// </summary>
        /// <param name="Filed">查询的字段</param>
        /// <param name="lambda">条件表达式</param>
        /// <returns></returns>
        public static string IC_Max_SQL(string Filed, LambdaExpression lambda)
        {
            string where = ExpressionProvider.ToSql(lambda.Body);
            return string.Format("select max(" + Filed + ") from {0} {1}", GetTables(lambda.Parameters), (!string.IsNullOrEmpty(where) ? " where " + where : ""));
        }

        /// <summary>
        /// 返回最小值
        /// </summary>
        /// <param name="Filed"></param>
        /// <param name="lambda"></param>
        /// <returns></returns>
        public static string IC_Min_SQL(string Filed, LambdaExpression lambda)
        {
            string where = ExpressionProvider.ToSql(lambda.Body);
            return string.Format("select Min(" + Filed + ") from {0} {1}", GetTables(lambda.Parameters), (!string.IsNullOrEmpty(where) ? " where " + where : ""));
        }


        #endregion

        #region 新增

        /// <summary>
        /// 生成新增SQL语句
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static SQLObject IC_Insert_SQL(object obj)
        {
            SQLObject Exec_SQL = new SQLObject();
            StringBuilder PortfolioSQL = new StringBuilder();
            StringBuilder PortfolioParm = new StringBuilder();
            DataObjectFieldAttribute dofa = new DataObjectFieldAttribute(false);
            DisplayNameAttribute Coloum = new DisplayNameAttribute();
            List<SqlParameter> Parms = new List<SqlParameter>();
            string Rel_Coloum = string.Empty;
            object ParamValue = null;
            try
            {
                foreach (PropertyDescriptor _pi in TypeDescriptor.GetProperties(obj))
                {
                    ParamValue = GetPropertyValue(obj, _pi.Name);
                    if (ParamValue != null)
                    {
                        dofa = (_pi.Attributes[typeof(DataObjectFieldAttribute)] as DataObjectFieldAttribute);
                        Coloum = (_pi.Attributes[typeof(DisplayNameAttribute)] as DisplayNameAttribute);
                        Rel_Coloum = !string.IsNullOrEmpty(Coloum.DisplayName) ? Coloum.DisplayName : _pi.Name;
                        if (ToDbTypeByBool(_pi.PropertyType))
                            ParamValue = DataConverter.CBoolean(ParamValue.ToString()) ? 1 : 0;
                        Parms.Add(new SqlParameter(Rel_Coloum, ParamValue));
                        if (dofa != null)
                        {
                            if (!dofa.IsIdentity)
                            {
                                PortfolioSQL.Append(Rel_Coloum + ",");
                                PortfolioParm.Append("@" + Rel_Coloum + ",");

                            }
                        }
                        else
                        {
                            PortfolioSQL.Append(Rel_Coloum + ",");
                            PortfolioParm.Append("@" + Rel_Coloum + ",");
                        }
                    }
                }
            }
            catch (Exception EX)
            {
                throw new Exception(EX.Message);
            }

            Exec_SQL.TSQL = string.Format("insert into {0}({1}) values({2})", new object[] { GetObjectBinderTableName(obj.GetType()), PortfolioSQL.ToString().TrimEnd(','), PortfolioParm.ToString().TrimEnd(',') });
            Exec_SQL.Parms = Parms.ToArray();
            return Exec_SQL;
        }

        #endregion

        #region 修改

        /// <summary>
        /// 生成更新对象
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static SQLObject IC_Update_SQL(object obj)
        {
            return IC_Update_SQL(obj, null);
        }

        /// <summary>
        /// 生成更新对象
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="_ParmaryKey"></param>
        /// <returns></returns>
        public static SQLObject IC_Update_SQL(object obj, string _ParmaryKey)
        {
            string ParmaryKey = _ParmaryKey;
            SQLObject Exec_SQL = new SQLObject();
            StringBuilder PortfolioParm = new StringBuilder();
            DataObjectFieldAttribute dofa = new DataObjectFieldAttribute(false);
            DisplayNameAttribute Coloum = new DisplayNameAttribute();
            List<SqlParameter> Parms = new List<SqlParameter>();
            string Rel_Coloum = string.Empty;
            object ParamValue = null;
            try
            {
                foreach (PropertyDescriptor _pi in TypeDescriptor.GetProperties(obj))
                {
                    ParamValue = GetPropertyValue(obj, _pi.Name);
                    if (ParamValue != null)
                    {
                        dofa = (_pi.Attributes[typeof(DataObjectFieldAttribute)] as DataObjectFieldAttribute);
                        Coloum = (_pi.Attributes[typeof(DisplayNameAttribute)] as DisplayNameAttribute);
                        Rel_Coloum = !string.IsNullOrEmpty(Coloum.DisplayName) ? Coloum.DisplayName : _pi.Name;
                        if (ToDbTypeByDateTime(_pi.PropertyType))
                            ParamValue = Check.ToDateTime(ParamValue);
                        if (ToDbTypeByBool(_pi.PropertyType))
                            ParamValue = DataConverter.CBoolean(ParamValue.ToString()) ? 1 : 0;
                        Parms.Add(new SqlParameter(Rel_Coloum, ParamValue));
                        if (dofa != null)
                        {
                            if (!dofa.PrimaryKey)
                                PortfolioParm.Append(Rel_Coloum + "=@" + Rel_Coloum + ",");
                            else
                            {
                                if (string.IsNullOrEmpty(ParmaryKey))
                                    ParmaryKey = Rel_Coloum;
                            }
                        }
                        else
                            PortfolioParm.Append(Rel_Coloum + "=@" + Rel_Coloum + ",");

                    }
                }
            }
            catch (Exception EX)
            {
                throw new Exception(EX.Message);
            }
            Exec_SQL.TSQL = string.Format("UpDate {0} set {1}  where {2}=@{2}", new object[] { GetObjectBinderTableName(obj.GetType()), PortfolioParm.ToString().TrimEnd(','), ParmaryKey });
            Exec_SQL.Parms = Parms.ToArray();
            return Exec_SQL;
        }

        #endregion

        #region 删除
        /// <summary>
        /// 删除语句
        /// </summary>
        /// <param name="obj">对象</param>
        ///  <param name="val">主键值</param>
        /// <returns></returns>
        public static SQLObject IC_Delete_SQL(object obj,object val)
        {
            return IC_Delete_SQL(GetObjectBinderTableName(obj.GetType()), GetParmary(obj),val, true);
        }

        /// <summary>
        /// 删除语句
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="notOrNonot"></param>
        /// <returns></returns>
        public static SQLObject IC_Delete_SQL(string TableName, string keyField, object val, bool notOrNonot)
        {
            SQLObject sql_boj = new SQLObject();
            if (notOrNonot)
            {
                sql_boj.TSQL = "delete from " + TableName + "  where " + keyField + "='" + val +"'" ;
                sql_boj.Parms = new SqlParameter[] { new SqlParameter(keyField, val) };
            }
            else
            {
                sql_boj.TSQL =string.Format( "delete from " + TableName + "  where " + keyField + " in ({0})",val);
                sql_boj.Parms = null;
            }
            return sql_boj;
        }

        #endregion

        /// <summary>
        /// 返回SQLObject对象
        /// </summary>
        /// <param name="Lambda">Lambda条件表达式</param>
        /// <returns></returns>
        public static SQLObject IC_Delete_SQL(LambdaExpression Lambda)
        {
            SQLObject Exec_SQL = new SQLObject();
            string where = ExpressionProvider.ToSql(Lambda.Body);
            Exec_SQL.TSQL = string.Format("delete {0} from {1} {2}", GetTablesAlias(Lambda.Parameters), GetTables(Lambda.Parameters), (!string.IsNullOrEmpty(where) ? " where " + where : ""));
            Exec_SQL.Parms = null;
            return Exec_SQL;
        }
        /// <summary>
        /// 主键查询
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="KeyVal"></param>
        /// <returns></returns>
        public static SQLObject IC_Delete_SQL(string Table, string Where)
        {
            SQLObject s_obj = new SQLObject();
            s_obj.TSQL = "delete  from " + Table + "  where " + Where;
            return s_obj;
        }
        #region 查询

        /// <summary>
        /// 主键查询
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="KeyVal"></param>
        /// <returns></returns>
        public static SQLObject IC_Select_Single_SQL(object obj, object KeyVal)
        {
            SQLObject s_obj = new SQLObject();
            string KeyP = GetParmary(obj);
            s_obj.Parms = new SqlParameter[] { new SqlParameter(KeyP, KeyVal) };
            s_obj.TSQL = "select top  1 *  from " + GetObjectBinderTableName(obj.GetType()) + "  where " + KeyP + "=@" + KeyP;
            return s_obj;
        }

        /// <summary>
        /// 指定键查询
        /// </summary>
        /// <param name="Field">字段名</param>
        /// <param name="KeyVal">值</param>
        /// <returns></returns>
        public static SQLObject IC_Select_Single_SQL(object obj, string Field, object KeyVal)
        {
            SQLObject s_obj = new SQLObject();
            s_obj.Parms = new SqlParameter[] { new SqlParameter(Field, KeyVal) };
            s_obj.TSQL = "select top  1 *  from " + GetObjectBinderTableName(obj.GetType()) + "  where " + Field + "=@" + Field;
            return s_obj;
        }

        /// <summary>
        /// 自定义分页查询
        /// </summary>
        /// <param name="obj">查询对象</param>
        /// <param name="query">分页对象</param>
        /// <param name="CheckModel">是否包含查询对象条件</param>
        /// <returns></returns>
        public static SQLObject IC_Select_SQL(object obj, QueryParam query, bool CheckModel)
        {
            SQLObject s_obj = new SQLObject();
            string where = (CheckModel) ? Combination(obj, query.Where) : query.Where;
            string KeyP = GetParmary(obj);
            string TableName = GetObjectBinderTableName(obj.GetType());
            SqlParameter[] Parameters ={
                   new  SqlParameter("@TableName", SqlDbType.VarChar, 8000),
                    new  SqlParameter("@ReturnFields", SqlDbType.VarChar,8000),
                     new  SqlParameter("@Where", SqlDbType.VarChar, 8000),
                     new  SqlParameter("@PageIndex", SqlDbType.Int),
                     new  SqlParameter("@PageSize", SqlDbType.Int),
                     new  SqlParameter("@Orderfld", SqlDbType.NVarChar, 500),
                     new  SqlParameter("@OrderType", SqlDbType.Int)
            };
            Parameters[0].Value = TableName;
            Parameters[1].Value = Input.GetDefault(query.ReturnFiled, "");
            Parameters[2].Value = Input.GetDefault(where, "");
            Parameters[3].Value = query.PageIndex > 0 ? query.PageIndex - 1 : 0;
            Parameters[4].Value = query.PageSize;
            Parameters[5].Value = query.OrderField;
            Parameters[6].Value = query.OrderType;
            s_obj.Parms = Parameters;
            s_obj.TSQL = "YTPage";
            return s_obj;
        }


        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public static SQLObject IC_Select_SQL(QueryParam query)
        {
            SQLObject s_obj = new SQLObject();
            SqlParameter[] Parameters ={
                   new  SqlParameter("@TableName", SqlDbType.VarChar, 8000),
                    new  SqlParameter("@ReturnFields", SqlDbType.VarChar,8000),
                     new  SqlParameter("@Where", SqlDbType.VarChar, 8000),
                     new  SqlParameter("@PageIndex", SqlDbType.Int),
                     new  SqlParameter("@PageSize", SqlDbType.Int),
                     new  SqlParameter("@Orderfld", SqlDbType.NVarChar, 500),
                     new  SqlParameter("@OrderType", SqlDbType.Int)
            };
            Parameters[0].Value = query.TableName;
            Parameters[1].Value = Input.GetDefault(query.ReturnFiled, "*");
            Parameters[2].Value = Input.GetDefault(query.Where, "");
            Parameters[3].Value = query.PageIndex > 0 ? query.PageIndex - 1 : 0;
            Parameters[4].Value = query.PageSize;
            Parameters[5].Value = query.OrderField;
            Parameters[6].Value = query.OrderType;
            s_obj.Parms = Parameters;
            s_obj.TSQL = "YTPage";
            return s_obj;
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public static SQLObject IC_Select_SQL1(QueryParam query)
        {
            SQLObject s_obj = new SQLObject();
            SqlParameter[] Parameters ={
                   new  SqlParameter("@SQLCONTENT", SqlDbType.VarChar, 8000),
                     new  SqlParameter("@PageIndex", SqlDbType.Int),
                     new  SqlParameter("@PageSize", SqlDbType.Int)
            };
            Parameters[0].Value = query.SQLCONTENT;
            Parameters[1].Value = query.PageIndex;
            Parameters[2].Value = query.PageSize;
            s_obj.Parms = Parameters;
            s_obj.TSQL = "YTPage1";
            return s_obj;
        }

        /// <summary>
        /// 模糊查询
        /// </summary>
        /// <param name="obj">查询对象</param>
        /// <param name="top">返回记录数，0为全部</param>
        /// <returns></returns>
        public static SQLObject IC_Select_SQL(object obj, int top, QueryParam query)
        {
            SQLObject Exec_SQL = new SQLObject();
            List<SqlParameter> Parms = new List<SqlParameter>();
            StringBuilder PortfolioParm = new StringBuilder();
            DisplayNameAttribute Coloum = new DisplayNameAttribute();
            string Rel_Coloum = string.Empty;
            string Order = string.Empty;
            object ParamValue = null;
            try
            {
                foreach (PropertyDescriptor _pi in TypeDescriptor.GetProperties(obj))
                {
                    ParamValue = GetPropertyValue(obj, _pi.Name);
                    if (ParamValue != null)
                    {
                        Coloum = (_pi.Attributes[typeof(DisplayNameAttribute)] as DisplayNameAttribute);
                        Rel_Coloum = !string.IsNullOrEmpty(Coloum.DisplayName) ? Coloum.DisplayName : _pi.Name;
                        if (ToDbTypeByBool(_pi.PropertyType))
                            ParamValue = DataConverter.CBoolean(ParamValue.ToString()) ? 1 : 0;
                        Parms.Add(new SqlParameter(Rel_Coloum, ParamValue));
                        if (_pi.PropertyType.Name.ToString().ToLower() != "string")
                        {
                            PortfolioParm.Append(Rel_Coloum + "=@" + Rel_Coloum + " and ");
                        }
                        else
                        {
                            PortfolioParm.Append(Rel_Coloum + " like '%'+@" + Rel_Coloum + "+'%' and ");
                        }

                    }
                }
                if (query != null && string.IsNullOrEmpty(query.OrderField))
                {
                    Order = string.Format("order by {0} {1}", query.OrderField,query.OrderType==1?"desc ":"asc ");
                }
            }
            catch (Exception EX)
            {
                throw new Exception(EX.Message);
            }

            string where = PortfolioParm.ToString().Trim().Trim("and".ToCharArray());
            Exec_SQL.TSQL = string.Format("select " + (top > 0 ? " top " + top : "") + " *  from {0} {1} {2}", new object[] { GetObjectBinderTableName(obj.GetType()), (where.Length > 0 ? " where " + where : "") ,Order});
            Exec_SQL.Parms = Parms.ToArray();
            return Exec_SQL;
        }

        /// <summary>
        /// 模糊查询
        /// </summary>
        /// <param name="obj">查询对象</param>
        /// <param name="top">返回记录数，0为全部</param>
        /// <returns></returns>
        public static SQLObject IC_Select_SQL(object obj, int top)
        {
            SQLObject Exec_SQL = new SQLObject();
            List<SqlParameter> Parms = new List<SqlParameter>();
            StringBuilder PortfolioParm = new StringBuilder();
            DisplayNameAttribute Coloum = new DisplayNameAttribute();
            string Rel_Coloum = string.Empty;
            object ParamValue = null;
            try
            {
                foreach (PropertyDescriptor _pi in TypeDescriptor.GetProperties(obj))
                {
                    ParamValue = GetPropertyValue(obj, _pi.Name);
                    if (ParamValue != null)
                    {
                        Coloum = (_pi.Attributes[typeof(DisplayNameAttribute)] as DisplayNameAttribute);
                        Rel_Coloum = !string.IsNullOrEmpty(Coloum.DisplayName) ? Coloum.DisplayName : _pi.Name;
                        if (ToDbTypeByBool(_pi.PropertyType))
                            ParamValue = DataConverter.CBoolean(ParamValue.ToString()) ? 1 : 0;
                        Parms.Add(new SqlParameter(Rel_Coloum, ParamValue));
                        if (_pi.PropertyType.Name.ToString().ToLower() != "string")
                        {
                            PortfolioParm.Append(Rel_Coloum + "=@" + Rel_Coloum + " and ");
                        }
                        else
                        {
                            PortfolioParm.Append(Rel_Coloum + " like '%'+@" + Rel_Coloum + "+'%' and ");
                        }

                    }
                }
            }
            catch (Exception EX)
            {
                throw new Exception(EX.Message);
            }

            string where = PortfolioParm.ToString().Trim().Trim("and".ToCharArray());
            Exec_SQL.TSQL = string.Format("select " + (top > 0 ? " top " + top : "") + " *  from {0} {1}", new object[] { GetObjectBinderTableName(obj.GetType()), (where.Length > 0 ? " where " + where : "") });
            Exec_SQL.Parms = Parms.ToArray();
            return Exec_SQL;
        }

        /// <summary>
        /// 单表多条件查询
        /// </summary>
        /// <param name="top">返回记录数，0为全部</param>
        /// <param name="Lambda">Lambda条件表达式</param>
        /// <returns></returns>
        public static SQLObject IC_Select_SQL(LambdaExpression Lambda)
        {
            return IC_Select_SQL(0, Lambda);
        }

        /// <summary>
        /// 返回SQLObject对象
        /// </summary>
        /// <param name="Lambda">Lambda条件表达式</param>
        /// <returns></returns>
        public static SQLObject IC_Select_SQL(int top, LambdaExpression Lambda)
        {
            SQLObject Exec_SQL = new SQLObject();
            string where = ExpressionProvider.ToSql(Lambda.Body);
            Exec_SQL.TSQL = string.Format("select " + (top > 0 ? " top " + top : "") + " * from {0} {1}", GetTables(Lambda.Parameters), (!string.IsNullOrEmpty(where) ? " where " + where : ""));
            Exec_SQL.Parms = null;
            return Exec_SQL;
        }

        /// <summary>
        /// 多表多条件查询
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="fun"></param>
        /// <returns></returns>
        public static string IC_Select_SQL(string[] fileds, LambdaExpression Lambda)
        {
            string where = ExpressionProvider.ToSql(Lambda.Body);
            StringBuilder tables = new StringBuilder();
            foreach (ParameterExpression pr in Lambda.Parameters)
            {
                tables.Append(GetObjectBinderTableName(pr.Type) + " " + pr.Name + ",");
            }
            StringBuilder selectFileds = new StringBuilder();
            if (fileds != null)
                selectFileds.Append(string.Join(" , ", fileds.Select(w => w.ToString()).ToArray()));
            else
                selectFileds.Append("*");

            return string.Format("select {0} from {1} {2}", selectFileds.ToString().Trim(','), tables.ToString().Trim(','), (!string.IsNullOrEmpty(where) ? " where " + where : ""));
        }

        /// <summary>
        /// 多表多条件查询
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="fun"></param>
        /// <returns></returns>
        public static string IC_Select_SQL(string returnField, LambdaExpression Lambda, string orderField)
        {
            string where = ExpressionProvider.ToSql(Lambda.Body);
            StringBuilder tables = new StringBuilder();
            foreach (ParameterExpression pr in Lambda.Parameters)
            {
                tables.Append(GetObjectBinderTableName(pr.Type) + " " + pr.Name + ",");
            }

            if (string.IsNullOrEmpty(returnField) == true)
            {
                returnField = "*";
            }

            return string.Format("select {0} from {1} {2} {3}", returnField, tables.ToString().Trim(','), (!string.IsNullOrEmpty(where) ? " where " + where : ""), (!string.IsNullOrEmpty(orderField) ? " order by " + orderField : ""));
        }

        

        #endregion

        #region 对象操作方法


        public static string GetTables(ReadOnlyCollection<ParameterExpression> parms)
        {
            StringBuilder tables = new StringBuilder();
            foreach (ParameterExpression pr in parms)
            {
                tables.Append(GetObjectBinderTableName(pr.Type) + " " + pr.Name + ",");
            }
            return tables.ToString().Trim(',');
        }

        /// <summary>
        /// 获取表的别名
        /// </summary>
        /// <param name="parms"></param>
        /// <returns></returns>
        public static string GetTablesAlias(ReadOnlyCollection<ParameterExpression> parms)
        {
            StringBuilder tables = new StringBuilder();
            foreach (ParameterExpression pr in parms)
            {
                tables.Append(pr.Name + ",");
            }
            return tables.ToString().Trim(',');
        }


        /// <summary>
        /// 对对象内条件进行组合
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="where"></param>
        /// <returns></returns>
        public static string Combination(object obj, string where)
        {
            if (obj != null)
            {
                StringBuilder PortfolioParm = new StringBuilder();
                DisplayNameAttribute Coloum = new DisplayNameAttribute();
                string Rel_Coloum = string.Empty;
                object ParamValue = null;
                try
                {
                    foreach (PropertyDescriptor _pi in TypeDescriptor.GetProperties(obj))
                    {
                        ParamValue = GetPropertyValue(obj, _pi.Name);
                        if (ParamValue != null)
                        {
                            Coloum = (_pi.Attributes[typeof(DisplayNameAttribute)] as DisplayNameAttribute);
                            Rel_Coloum = !string.IsNullOrEmpty(Coloum.DisplayName) ? Coloum.DisplayName : _pi.Name;
                            if (ToDbTypeByBool(_pi.PropertyType))
                                ParamValue = DataConverter.CBoolean(ParamValue.ToString()) ? 1 : 0;
                            if (_pi.PropertyType.Name.ToString().ToLower() != "string" || Rel_Coloum.IndexOf("ID") >= 0 || Rel_Coloum.ToLower()=="deleted")
                                PortfolioParm.Append(" and " + Rel_Coloum + "='" + ParamValue + "'");
                            else
                                PortfolioParm.Append(" and " + Rel_Coloum + " like '%" + ParamValue + "%'");

                        }
                    }
                }
                catch (Exception EX)
                {
                    throw new Exception(EX.Message);
                }
                where = (!string.IsNullOrEmpty(where) ? (where + PortfolioParm.ToString()) : PortfolioParm.ToString().Trim().Trim("and".ToCharArray()));
            }

            return (where.Length > 0) ? " where" + where : "";
        }

        /// <summary>
        /// 获取对象主键
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string GetParmary(object obj)
        {
            string ParmaryKey = "ID";
            DataObjectFieldAttribute dofa = new DataObjectFieldAttribute(false);
            DisplayNameAttribute Coloum = new DisplayNameAttribute();
            foreach (PropertyDescriptor _pi in TypeDescriptor.GetProperties(obj))
            {
                Coloum = (_pi.Attributes[typeof(DisplayNameAttribute)] as DisplayNameAttribute);
                dofa = (_pi.Attributes[typeof(DataObjectFieldAttribute)] as DataObjectFieldAttribute);
                if (dofa != null)
                {
                    ParmaryKey = !string.IsNullOrEmpty(Coloum.DisplayName) ? Coloum.DisplayName : _pi.Name;
                    break;
                }

            }
            return ParmaryKey;
        }

        /// <summary>
        /// 实体绑定数据表名
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static string GetObjectBinderTableName(Type type)
        {
            DescriptionAttribute dpa = (DescriptionAttribute)type.GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault();
            if (dpa != null)
            {
                if (dpa.Description != "")
                    return dpa.Description;
                else
                    new Exception("对象未绑定数据表");
            }



            return type.Name;
        }

        /// <summary>
        /// 得到对象内的属性值
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="property"></param>
        /// <returns></returns>
        private static object GetPropertyValue(object obj, string property)
        {
            Type type = obj.GetType();
            PropertyInfo info = type.GetProperty(property);
            if (info == null)
            {
                return null;
            }
            return info.GetValue(obj, null);
        }

        #endregion

        #region 一般方法

        /// <summary>
        /// 判断数据是否为Bool
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static bool ToDbTypeByBool(Type type)
        {
            Type columnType = type;
            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
                columnType = type.GetGenericArguments()[0];

            if (columnType == typeof(bool))
                return true;
            return false;
        }
        /// <summary>
        /// 判断数据是否为DateTime
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static bool ToDbTypeByDateTime(Type type)
        {
            Type columnType = type;
            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
                columnType = type.GetGenericArguments()[0];

            if (columnType == typeof(DateTime) || columnType == typeof(DateTime?))
                return true;
            return false;
        }
        #endregion


    }
}
